from datetime import datetime
from typing import Any

from fastapi.encoders import jsonable_encoder
from typing_extensions import Optional

from app.utils.time_utils import now_time


# from app.startup.json_encoder import  custom_encoder

def custom_datetime_encoder(dt: datetime) -> str:
    return dt.strftime("%Y-%m-%d %H:%M:%S")


custom_encoder = {
    datetime: custom_datetime_encoder,
}


def test001():
    from http import HTTPStatus
    from typing import Any, Optional

    from pydantic import BaseModel

    MSG_OK = '操作成功'

    MSG_ERR = "API调用失败"

    # API返回的响应结果
    class BaseResult(BaseModel):
        # 提示信息
        msg: str = MSG_OK
        # 状态码,200为成功,其它皆为失败
        code: int = HTTPStatus.OK
        # 返回的数据信息
        data: Optional[Any] = None

        def json_encoders(self):
            model_dict = dict(self.__dict__)
            if self.data:
                if hasattr(self.data, 'json_encoders'):
                    # print(str_prominent('data has json_encoders'))
                    model_dict['data'] = self.data.json_encoders()
            return jsonable_encoder(model_dict, custom_encoder=custom_encoder)

    def okResult(data: Any = None, msg: str = MSG_OK):
        return BaseResult(code=HTTPStatus.OK, data=data, msg=msg)

    def errResult(data: Any = None, msg: str = MSG_ERR):
        return BaseResult(code=HTTPStatus.INTERNAL_SERVER_ERROR, data=data, msg=msg)

    from sqlalchemy.orm import relationship
    from sqlalchemy import Boolean, String
    from fastapi.encoders import jsonable_encoder
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, TIMESTAMP
    from datetime import datetime


    Base = declarative_base()

    class TimestampMixin:
        created_at = Column(TIMESTAMP, default=now_time, nullable=False)
        # DateTime  TIMESTAMP
        updated_at = Column(TIMESTAMP, default=now_time, onupdate=now_time, nullable=False)

        def to_dict(self) -> dict:
            model_dict = dict(self.__dict__)
            del model_dict['_sa_instance_state']
            return model_dict

        def to_dict_use_result(self) -> dict:
            model_dict = self.to_dict()
            return model_dict

        def json_encoders(self):
            # print(str_prominent('json_encoders'))
            model_dict = self.to_dict_use_result()
            return jsonable_encoder(model_dict, custom_encoder=custom_encoder)

    class User(Base, TimestampMixin):
        __tablename__ = "users"

        id = Column(Integer, primary_key=True, index=True)
        email = Column(String(255), unique=True, index=True, nullable=False)
        username = Column(String(255), unique=True, index=True, nullable=False)
        nickname = Column(String(255), unique=True, index=True, nullable=False)
        hashed_password = Column(String(255), nullable=False)
        is_active = Column(Boolean, default=True)
        is_superuser = Column(Boolean, default=False)


        # 查询的数据转字典

        def to_dict_use_result(self) -> dict:
            model_dict = super().to_dict_use_result()
            del model_dict['hashed_password']
            return model_dict

    user_data={
        'create_time': datetime.now()
    }
    user_data=User(
        id=1,
        username='admin',
        hashed_password="sdad",
        nickname='admin',
        email='admin@qq.com',
        is_active=True,
        is_superuser=True,
        created_at=datetime.now(),
        updated_at=datetime.now(),
    )
    result = okResult(data=user_data)
    jsonStr=result.json_encoders()
    print(jsonStr)


def test002():

    from pydantic import BaseModel
    from pydantic import ConfigDict
    class User(BaseModel):
        id: int = 1
        username: str = 'admin'
        hashed_password: str = "sdad"
        nickname: str = 'admin'
        email: str = 'admin@qq.com'
        is_active: bool = True
        is_superuser: bool = True
        created_at: datetime = datetime.now()
        updated_at: datetime = datetime.now()

        # from_attributes 将告诉 Pydantic 模型读取数据，即它不是一个 dict，而是一个 ORM 模型
        # https://docs.pydantic.dev/2.0/usage/models/#arbitrary-class-instances
        # 添加自定义 json 编码器来重新格式化时间
        model_config = ConfigDict(
            from_attributes=True,
            json_encoders=custom_encoder
        )

    class BaseResult(BaseModel):
        # 提示信息
        msg: str = 'OK'
        # 状态码,200为成功,其它皆为失败
        code: int = 200
        # 返回的数据信息
        data: Optional[Any] = None

    user_data=User()
    result = BaseResult(data=user_data)
    jsonStr=jsonable_encoder(result, custom_encoder=custom_encoder)
    print(jsonStr)


if __name__ == '__main__':
    test001()
    test002()
